/* eslint-disable */
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Card, Table, Row, Col, Button, Typography, Divider, Avatar, Tag, Statistic } from 'antd';
import { Line } from '@ant-design/plots';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import { UserOutlined, HomeOutlined, PhoneOutlined, TeamOutlined, ArrowLeftOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

const StudentProfile = () => {
  const [profileData, setProfileData] = useState(null);
  const [assessments, setAssessments] = useState([]);
  const [familyInfo, setFamilyInfo] = useState(null);
  const { studentId } = useParams();
  const navigate = useNavigate();

  const axiosInstance = axios.create({
    baseURL: 'http://47.111.104.30:8080',
    headers: {
      'Authorization': `Bearer ${localStorage.getItem('token')}`,
      'Content-Type': 'application/json'
    }
  });

  useEffect(() => {
    axiosInstance.get(`/api/v2/students/${studentId}`)
      .then(response => setProfileData(response.data))
      .catch(error => console.error('Error fetching student profile:', error));

    axiosInstance.get(`/api/v2/assessments/student/${studentId}`)
      .then(response => {
        const formattedData = response.data.map(assessment => ({
          ...assessment,
          submittedTime: new Date(assessment.submittedTime).toLocaleDateString()
        }));
        setAssessments(formattedData);
      })
      .catch(error => console.error('Error fetching assessments:', error));

    axiosInstance.get(`/api/familymessage/student/${studentId}`)
      .then(response => {
        if (response.data && response.data.length > 0) {
          setFamilyInfo(response.data[0]);
        }
      })
      .catch(error => console.error('Error fetching family info:', error));
  }, [studentId]);

  const getLatestScore = () => {
    if (assessments.length === 0) return null;
    return assessments[assessments.length - 1].score;
  };

  const getScoreTrend = () => {
    if (assessments.length < 2) return null;
    const lastScore = assessments[assessments.length - 1].score;
    const previousScore = assessments[assessments.length - 2].score;
    return lastScore > previousScore ? 'increase' : 'decrease';
  };

  const config = {
    data: assessments,
    xField: 'submittedTime',
    yField: 'score',
    smooth: true,
    point: {
      size: 5,
      shape: 'diamond',
      style: {
        fill: '#1890ff',
        stroke: '#fff',
        lineWidth: 2,
      },
    },
    label: {
      style: {
        fill: '#595959',
        fontSize: 12,
      },
    },
    title: {
      text: '心理测评分数趋势',
      style: {
        fontSize: 18,
        fontWeight: 'bold',
        fill: '#262626',
      },
    },
  };

  const cardStyle = {
    borderRadius: '16px',
    boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
    transition: 'all 0.3s ease',
    background: 'linear-gradient(145deg, #ffffff 0%, #f8f9ff 100%)',
    border: 'none',
    marginBottom: '24px',
    '&:hover': {
      boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
      transform: 'translateY(-2px)',
    }
  };

  const InfoItem = ({ label, value, icon }) => (
    <div style={{ 
      marginBottom: '16px',
      padding: '8px 12px',
      borderRadius: '8px',
      background: 'rgba(24, 144, 255, 0.05)',
      transition: 'all 0.3s ease',
      ':hover': {
        background: 'rgba(24, 144, 255, 0.1)',
      }
    }}>
      {icon && <span style={{ marginRight: '12px', color: '#1890ff' }}>{icon}</span>}
      <Text strong style={{ color: '#333' }}>{label}：</Text>
      <Text>{value || '暂无数据'}</Text>
    </div>
  );

  InfoItem.propTypes = {
    label: PropTypes.string.isRequired,
    value: PropTypes.string,
    icon: PropTypes.element,
  };

  const pageStyle = {
    padding: '32px',
    background: 'linear-gradient(135deg, #f0f2f5 0%, #e6f7ff 100%)',
    minHeight: '100vh',
  };

  const headerStyle = {
    textAlign: 'center',
    marginBottom: '32px',
    position: 'relative',
  };

  const titleStyle = {
    margin: '0',
    color: '#1890ff',
    fontSize: '32px',
    fontWeight: 'bold',
    textShadow: '0 2px 4px rgba(0,0,0,0.1)',
    background: 'linear-gradient(45deg, #1890ff, #69c0ff)',
    WebkitBackgroundClip: 'text',
    WebkitTextFillColor: 'transparent',
  };

  return (
    <div style={pageStyle}>
      <div style={headerStyle}>
        <Button 
          type="primary" 
          icon={<ArrowLeftOutlined />}
          onClick={() => navigate(-1)}
          style={{
            position: 'absolute',
            left: 0,
            top: '50%',
            transform: 'translateY(-50%)',
            borderRadius: '8px',
          }}
        >
          返回
        </Button>
        <Title level={2} style={titleStyle}>学生心理档案</Title>
      </div>

      <Row gutter={24}>
        <Col span={8}>
          <Card style={cardStyle}>
            <div style={{ 
              textAlign: 'center', 
              marginBottom: '24px',
              padding: '20px 0',
              background: 'linear-gradient(145deg, #e6f7ff 0%, #ffffff 100%)',
              borderRadius: '12px',
            }}>
              <Avatar 
                size={96} 
                icon={<UserOutlined />} 
                style={{
                  background: 'linear-gradient(45deg, #1890ff, #69c0ff)',
                  boxShadow: '0 4px 12px rgba(24,144,255,0.3)',
                }}
              />
              <Title level={3} style={{ marginTop: '16px', marginBottom: '8px', color: '#1890ff' }}>
                {profileData?.name}
              </Title>
              <Tag color="blue" style={{ padding: '4px 12px', borderRadius: '12px' }}>
                {profileData?.major}
              </Tag>
            </div>
            <Divider style={{ margin: '16px 0' }} />
            <InfoItem label="学号" value={profileData?.number} />
            <InfoItem label="性别" value={profileData?.gender} />
            <InfoItem label="出生日期" value={profileData?.birthDate} />
            <InfoItem label="年级" value={profileData?.grade} />
            <InfoItem label="学院" value={profileData?.college} />
            <InfoItem label="联系地址" value={profileData?.address} icon={<HomeOutlined />} />
          </Card>

          <Card
            title={
              <span style={{ 
                fontSize: '18px', 
                fontWeight: 'bold',
                background: 'linear-gradient(45deg, #1890ff, #69c0ff)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
              }}>
                家长信息
              </span>
            }
            style={cardStyle}
          >
            <InfoItem label="父亲姓名" value={familyInfo?.fatherName} icon={<TeamOutlined />} />
            <InfoItem label="父亲电话" value={familyInfo?.fatherPhone} icon={<PhoneOutlined />} />
            <InfoItem label="母亲姓名" value={familyInfo?.motherName} icon={<TeamOutlined />} />
            <InfoItem label="母亲电话" value={familyInfo?.motherPhone} icon={<PhoneOutlined />} />
            <InfoItem label="家庭住址" value={familyInfo?.homeAddress} icon={<HomeOutlined />} />
          </Card>
        </Col>

        <Col span={16}>
          <Card
            title={
              <div style={{ 
                display: 'flex', 
                justifyContent: 'space-between', 
                alignItems: 'center',
                padding: '8px 0',
              }}>
                <span style={{ 
                  fontSize: '18px', 
                  fontWeight: 'bold',
                  background: 'linear-gradient(45deg, #1890ff, #69c0ff)',
                  WebkitBackgroundClip: 'text',
                  WebkitTextFillColor: 'transparent',
                }}>
                  心理健康分析
                </span>
                <div style={{ display: 'flex', gap: '24px' }}>
                  <Statistic 
                    title="最新得分"
                    value={getLatestScore()}
                    valueStyle={{ 
                      color: '#1890ff',
                      fontSize: '24px',
                      fontWeight: 'bold',
                    }}
                  />
                  {getScoreTrend() && (
                    <Statistic 
                      title="趋势"
                      value={getScoreTrend() === 'increase' ? '上升' : '下降'}
                      valueStyle={{ 
                        color: getScoreTrend() === 'increase' ? '#3f8600' : '#cf1322',
                        fontSize: '24px',
                        fontWeight: 'bold',
                      }}
                    />
                  )}
                </div>
              </div>
            }
            style={cardStyle}
          >
            <div style={{ height: '400px', padding: '20px 0' }}>
              <Line {...config} />
            </div>
          </Card>

          <Card
            title={
              <span style={{ 
                fontSize: '18px', 
                fontWeight: 'bold',
                background: 'linear-gradient(45deg, #1890ff, #69c0ff)',
                WebkitBackgroundClip: 'text',
                WebkitTextFillColor: 'transparent',
              }}>
                历史测评记录
              </span>
            }
            style={cardStyle}
          >
            <Table
              columns={[
                { 
                  title: '测评日期', 
                  dataIndex: 'submittedTime', 
                  key: 'submittedTime',
                  align: 'center',
                },
                { 
                  title: '测评分数', 
                  dataIndex: 'score', 
                  key: 'score',
                  align: 'center',
                  render: (score) => (
                    <Tag 
                      color={score >= 60 ? 'success' : 'error'}
                      style={{
                        padding: '4px 12px',
                        borderRadius: '12px',
                        fontSize: '14px',
                      }}
                    >
                      {score}
                    </Tag>
                  )
                },
                { 
                  title: '评估结果', 
                  dataIndex: 'evaluation', 
                  key: 'evaluation',
                  align: 'center',
                },
              ]}
              dataSource={assessments}
              rowKey="id"
              pagination={{ 
                pageSize: 5,
                style: { marginTop: '16px' },
              }}
              style={{
                borderRadius: '12px',
                overflow: 'hidden',
              }}
            />
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default StudentProfile;